package root.controller.administration;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.RequestMap;
import org.slim3.util.ThrowableUtil;

import root.model.Note;
import root.service.OnetimeService;
import root.until.RequestAction;

public class NodeController extends Controller {
    OnetimeService oService = new OnetimeService();

    @Override
    public Navigation run() throws Exception {
        String action = request.getParameter("action");
        System.out.println("action : " + action);
        Map<String, Object> data = new HashMap<String, Object>();
        if (action != null) {
            switch (action) {
            case RequestAction.ADD_NOTE:
                // add new node
                Note note = oService.add(new RequestMap(request));
                data.put("node", note);
                this.json(data);
                break;
            case RequestAction.EDIT_NOTE:
                // edit note
                Note editNote = oService.edit(new RequestMap(request));
                data.put("note", editNote);
                break;
            case RequestAction.DELETE_NOTE:
                // delete note
                boolean success = oService.delete(new RequestMap(request));
                data.put("result", success);
                break;
            default:
                break;
            }
            return null;
        }
        // page load
        List<Note> listNote = oService.getListNote();
        requestScope("listNote", listNote);
        return forward("node.jsp");
    }

    /**
     * encode json
     * 
     * @author tuvv
     * @param data
     *            : Object
     * @return
     * 
     * */
    private void json(Object data) {
        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        response.setContentType("application/json; charset=" + encoding);
        try {
            PrintWriter out = null;
            try {
                out =
                    new PrintWriter(new OutputStreamWriter(
                        response.getOutputStream(),
                        encoding));
                out.print(JSON.encode(data));
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            ThrowableUtil.wrapAndThrow(e);
        }
    }
}